﻿using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace Gavel.Common.Component.Helper;

/// <summary>
/// 装饰器容器
/// </summary>
/// <param name="element">用户界面元素</param>
public class AdornerContainer(UIElement element) : Adorner(element)
{
    /// <summary>
    /// 子页面元素
    /// </summary>
    private UIElement? _child;

    /// <summary>
    /// 子页面元素
    /// </summary>
    public UIElement? Child
    {
        get => _child;
        set
        {
            if (value is null)
            {
                RemoveVisualChild(_child);
                _child = value;
                return;
            }

            AddVisualChild(value);
            _child = value;
        }
    }

    /// <summary>
    /// 可见子元素数量
    /// </summary>
    protected override int VisualChildrenCount => _child is not null ? 1 : 0;

    /// <summary>
    /// 定位子元素并确定FrameworkElement派生类的大小
    /// </summary>
    /// <param name="finalSize">父元素中的最后一个区域，这个元素应该用来排列它自己和它的子元素</param>
    /// <returns>实际使用的尺寸</returns>
    protected override Size ArrangeOverride(Size finalSize)
    {
        _child?.Arrange(new Rect(finalSize));
        return finalSize;
    }

    /// <summary>
    /// 从子元素集合中返回指定索引处的子元素
    /// </summary>
    /// <param name="index">集合中请求的子元素的从零开始的索引</param>
    /// <returns>请求的子元素</returns>
    protected override Visual GetVisualChild(int index)
    {
        if (index == 0 && _child != null)
        {
            return _child;
        }

        return base.GetVisualChild(index)!;
    }
}